package com.commit.service.impl;

import com.commit.domain.Answer;
import com.commit.domain.Question;
import com.commit.mapper.AnswerMapper;
import com.commit.ownException.NotFoundException;
import com.commit.service.AnsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

/**
 * @author:zyh
 * @Time:2021-02-28-14:51
 * @email:1269231889@qq.com
 */
@Service
public class AnsServiceImpl implements AnsService {
    @Autowired
    private AnswerMapper answerMapper;

    @Override
    public List<Answer> findByQuesId(Integer id) {
        List<Answer> byQuesId = answerMapper.findByQuesId(id);
        if(byQuesId==null||byQuesId.isEmpty()){
            throw new NotFoundException("没有回答");
        }
        return answerMapper.findByQuesId(id);
    }

    @Override
    public void save(Answer answer, HttpSession session) {
        Question question = (Question) session.getAttribute("question");
        answer.setUserId(question.getUserId());
        answer.setQuestionId(question.getId());
        answer.setCreateTime(new Date());
        answerMapper.saveAns(answer);
    }

    @Override
    public void update(Answer answer) {
        answerMapper.update(answer);
    }

    @Override
    public Answer findOne(Integer id) {
        return answerMapper.findOne(id);
    }

    @Override
    public List<Answer> findByTitle(String title) {
        List<Answer> byQuestion = answerMapper.findByQuestion(title);
        if(byQuestion==null||byQuestion.isEmpty()){
            throw new NotFoundException("没有回答");
        }
        return byQuestion;
    }

    @Override
    public Answer findByAccept(String title) {
        Answer accept = answerMapper.isAccept(title);
        if(accept==null){
            throw new NotFoundException("没有");
        }
        return accept;
    }

    @Override
    public List<Answer> showHighLikes(String title, Integer likes) {
        List<Answer> answers = answerMapper.highLikes(title);
        if(answers==null||answers.isEmpty()){
            throw new NotFoundException("没有回答列表");
        }
        List<Answer> high = new LinkedList<>();
        for(Answer answer:answers){
            if(answer.getLikes()>=likes){
                high.add(answer);
            }
        }
        if(high.isEmpty()){
            throw new NotFoundException("建议减低likes设置");
        }
        return high;
    }


}
